package com.xujianlong.utils;

import com.alibaba.fastjson.JSONObject;
import com.xujianlong.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/*
查询的维度信息都是不同的表和不同的key，因此我们可以在封装一层只传这两个参数的方法，并且这样查完只有一行数据
 */
public class DimUtil {
    public static JSONObject getDimInfo(Connection connection, String table, String key) throws Exception {
        //查询Redis
        Jedis jedis=RedisUtil.getJedis();
        String redisKey="DIM"+table+":"+key;
        String jsonStr = jedis.get(redisKey);
        if(jsonStr!=null){
            jedis.expire(redisKey,24*60*60);
            jedis.close();
            return JSONObject.parseObject(jsonStr);
        }


        //拼接sql
        String sql="select * from "+ GmallConfig.HBASE_SCHEMA+"."+
                table+" where id='"+key+"'";

        System.out.println("查询的Sql为："+sql);
        //从Hbase查询数据
        List<JSONObject> list = JdbcUtil.queryData(connection, sql, JSONObject.class, false);

        //System.out.println("查询的结果为："+list.get(0));
        //写入Redis
        JSONObject dimInfo = list.get(0);

        jedis.set(redisKey,dimInfo.toJSONString());
        jedis.expire(redisKey,24*60*60);
        jedis.close();

        //返回结果
        return list.get(0);
    }
    public static void delDimInfo(String table,String id){
        Jedis jedis = RedisUtil.getJedis();
        jedis.del("DIM"+table+":"+id);

        jedis.close();
    }
    public static void updateDimInfo(String table,String id,String value){
        Jedis jedis = RedisUtil.getJedis();
        jedis.set("DIM"+table+":"+id,value);

        jedis.close();
    }

    public static void main(String[] args) throws Exception {
        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        long start = System.currentTimeMillis();
        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "18"));
        long end1 = System.currentTimeMillis();
        System.out.println(getDimInfo(connection, "DIM_BASE_TRADEMARK", "18"));
        long end2 = System.currentTimeMillis();


        System.out.println(end1 - start);
        System.out.println(end2 - end1);
        connection.close();
    }
}
